package com.example.socket.server;

import com.example.socket.core.*;
import com.example.socket.handler.Dispatcher;
import com.example.socket.parameter.ResultCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author frank
 * @param <T>
 */
public class ResponseResultCallback<T> implements ResultCallback<T> {
    private static Logger logger = LoggerFactory.getLogger(ResponseResultCallback.class);

    private Dispatcher dispatcher;
    private Session session;
    private Request<?> request;

    ResponseResultCallback(Dispatcher dispatcher, Session session, Request<?> request) {
        this.dispatcher = dispatcher;
        this.session = session;
        this.request = request;
    }

    @Override
    public void call(T processRet) {
        Header requestHeader = request.getHeader();
        requestHeader.setSession(session.getId());
        requestHeader.addState(MessageConstant.STATE_RESPONSE);
        // 处理结果编码
        Response<?> response;
        if (processRet != null && processRet.getClass() == Response.class) {
            Response<?> paramResp = (Response<?>) processRet;
            Object body = paramResp.getBody();
            response = Response.valueOf(requestHeader, body);
        } else {
            response = Response.valueOf(requestHeader, processRet);
        }
        // 封装回应信息体
        Message message = dispatcher.encodeResonse(response);
        if (logger.isDebugEnabled()) {
            logger.debug("[会话:{} 请求{}]的回应CALL_BACK，信息体[{}]", new Object[]{session.getId(), request.getCommand(), new String(message.getBody())});
        }
        // 向会话回写回应
        dispatcher.send(message, session);
    }
}
